package com.woniu.backstage.controller;

import com.woniu.backstage.common.Result;
import com.woniu.backstage.entity.TbManager;
import com.woniu.backstage.exception.LoginException;
import com.woniu.backstage.service.ITbManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author spirit
 * @since 2020-04-15
 */
@RestController
public class TbManagerController {
    @Autowired
    private ITbManagerService managerService;

    @PostMapping("login")
    public Result login(String username, String password, HttpServletRequest request) throws Exception {
        System.out.println(username);
        System.out.println(password);
        //判断管理员名和密码不能为空
        if(username == null || password == null || username==""|| password==""){
            throw new LoginException("管理员名或密码不能为空");
        }
        TbManager manager = managerService.getManager(username, password);
        //判断管理员账号是否存在
        if(manager == null){
            throw new LoginException("管理员名或密码错误");
        }else{
            if(manager.getStatus().equals("异常")){
                throw new LoginException("管理员状态异常");
            }else{
                manager.setRootTime(new Date());
                managerService.updateById(manager);
                //如果管理员账号存在则进行登录
                HttpSession session = request.getSession();
                session.setAttribute("manager",manager);
                return Result.success(manager,1);
            }
        }
    }

    @RequestMapping("/managerShow")
    public Result managerShow(){
        List<TbManager> managers = managerService.getManagers();
        return Result.success(managers,1);
    }

    @RequestMapping("updateById")
    public Result updateById(TbManager manager){
        System.out.println("进入更新请求");
        System.out.println("修改的内容："+manager);
        boolean result = managerService.updateById(manager);
        if(result){
            return Result.success();
        }else{
            return Result.fail();
        }
    }
}

